//
//  BKGDMainViewController.m
//  bestkeep
//
//  Created by 武探 on 2016/11/10.
//  Copyright © 2016年 utouu. All rights reserved.
//

#import "BKGDMainViewController.h"
#import "BKGDManagerViewController.h"
#import "BKGDMainBottomView.h"
#import "BKGDImageBrowserView.h"
#import "BKGDPopupViewController.h"
#import "UIScrollView+BKGDHeader.h"
#import "BKGDCell.h"
#import "WUMenuView.h"
#import "Mediator+BKMy.h"
#import "Mediator+BKOrder.h"
#import "BKGDBecomeVIPViewController.h"
#import "BKGDMainFooterRefreshView.h"
#import "Mediator+BKSC.h"
#import "RootNavigationController.h"
#import "BKGDSpecificationController.h"
#import "BKGDPromotionsViewController.h"
#import "HUD.h"
#import "BKGDAddPriceBuyViewController.h"


NSString *const BKGDMainViewHeaderSectionViewIdentifier = @"BKGDMainViewHeaderSectionViewIdentifier";
NSString *const BKGDMainViewFooterSectionViewIdentifier = @"BKGDMainViewFooterSectionViewIdentifier";

@interface BKGDMainViewController ()<UITableViewDelegate, UITableViewDataSource, BKGDMainBottomViewDelegate, UIAlertViewDelegate, BKGDEvaluationCellDelegate, BKGDSubPriceCellDelegate, BKGDSpecificationControllerDelegate>

@property(nonatomic,strong) UITableView *tableView;
@property(nonatomic,strong) NSMutableArray<SectionModel*> *dataArray;

@property(nonatomic,strong) BKGDImageBrowserView *imageBrowserView;
@property(nonatomic,strong) BKGDMainBottomView *bottomView;
@property(nonatomic,strong) UINavigationController *popupNavigationController;

@property(nonatomic,strong) BKGDSpecificationController *specificationController;

@property(nonatomic,strong) NSIndexPath *skuCellIndexPath;
@property(nonatomic,strong) NSIndexPath *priceCellIndexPath;
@property(nonatomic,strong) NSIndexPath *subPriceCellIndexPath;

@property (nonatomic, strong) UIView *maskView;

@end

@implementation BKGDMainViewController

-(void)viewDidLoad {
    [super viewDidLoad];
    
    [self addMaskImageView];
    
    [self initializeComponent];
}

-(void)viewWillDisappear:(BOOL)animated {
    [super viewWillDisappear:animated];
    if (_maskView) {
        [_maskView removeFromSuperview];
    }
}

-(void)addMaskImageView{
    if (![_goodsCoverImg isEqualToString:@""]) {
        _maskView = [[UIView alloc] initWithFrame:CGRectMake(0, 64, SCREENWIDTH, ScreenHeight)];
        _maskView.backgroundColor = [UIColor whiteColor];
        UIImageView *imageView = [[UIImageView alloc] initWithFrame:CGRectMake(0, 0, SCREENWIDTH, SCREENWIDTH)];
        imageView.image = [CacheImage imageFromKey:_goodsCoverImg];
        imageView.contentMode = UIViewContentModeScaleAspectFill;
        [_maskView addSubview:imageView];
        [[UIApplication sharedApplication].keyWindow addSubview:_maskView];
    }
}

/**
 初始化组件
 */
- (void)initializeComponent {
//    self.view.backgroundColor = [UIColor whiteColor];
    
    _dataArray = [NSMutableArray array];
    
    _tableView = [[UITableView alloc] initWithFrame:self.view.bounds style:UITableViewStyleGrouped];
    _tableView.delegate = self;
    _tableView.dataSource = self;
    _tableView.separatorStyle = UITableViewCellSeparatorStyleNone;
    _tableView.backgroundColor = [UIColor colorWithRed:0.949 green:0.949 blue:0.949 alpha:1.00];
    _tableView.showsVerticalScrollIndicator = NO;
    [_tableView registerClass:[UITableViewHeaderFooterView class] forHeaderFooterViewReuseIdentifier:BKGDMainViewHeaderSectionViewIdentifier];
    [_tableView registerClass:[UITableViewHeaderFooterView class] forHeaderFooterViewReuseIdentifier:BKGDMainViewFooterSectionViewIdentifier];
    [self.view addSubview:_tableView];
    
    BKGDMainFooterRefreshView *footerView = [[BKGDMainFooterRefreshView alloc] init];
    footerView.hidden = YES;
    _tableView.tableFooterView = footerView;
    _tableView.contentInset = UIEdgeInsetsMake(0, 0, -(CGRectGetHeight(footerView.frame) - 32), 0);
    
    CGFloat imageWidth = CGRectGetWidth([[UIScreen mainScreen] bounds]);
    _imageBrowserView = [[BKGDImageBrowserView alloc] initWithFrame:CGRectMake(0, 0, imageWidth, imageWidth)];
    _imageBrowserView.goodsCoverImg = _goodsCoverImg;
    _tableView.BKGD_headerView = _imageBrowserView;
    
    _bottomView = [[BKGDMainBottomView alloc] init];
    _bottomView.delegate = self;
    
    [self makeConstraints];
    
    if ([_goodsId rangeOfString:@"?"].location != NSNotFound) {
        NSString *goodsStr = _goodsId;
        _goodsId = [_goodsId substringToIndex:[_goodsId rangeOfString:@"?"].location];
        NSString *shopInfo = [goodsStr substringFromIndex:[goodsStr rangeOfString:@"?"].location + 1];
        NSArray *a = [shopInfo componentsSeparatedByString:@"&"];
        NSMutableArray *mA = [NSMutableArray array];
        for (NSString *s in a) {
            if (([s rangeOfString:@"storeId"].location != NSNotFound) || ([s rangeOfString:@"shopKeeper"].location != NSNotFound)) {
                NSArray *a = [s componentsSeparatedByString:@"="];
                [mA addObject:a.lastObject];
            }
        }
        _storeId = mA.firstObject;
        _shopKeeper = mA.lastObject;
        [mA removeAllObjects];
    }
    
    [self requestGoodsDetailData];
    
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(taxCellHelpNotification:) name:BKGDTaxCellHelpNotificationKey object:nil];
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(popBKGDManagerHandler:) name:RootNavigationDidPopViewControllerNotification object:nil];
}

/**
 创建约束
 */
-(void)makeConstraints {
    [_tableView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.edges.equalTo(self.view).insets(UIEdgeInsetsZero);
    }];
}

-(void)setContentInsets:(UIEdgeInsets)contentInsets {
    _tableView.contentInset = contentInsets;
}

-(UIEdgeInsets)contentInsets {
    return _tableView.contentInset;
}

-(void)setScrollIndicatorInsets:(UIEdgeInsets)scrollIndicatorInsets {
    _tableView.scrollIndicatorInsets = scrollIndicatorInsets;
}

-(UIEdgeInsets)scrollIndicatorInsets {
    return _tableView.scrollIndicatorInsets;
}

#pragma -mark tableView delegate

-(NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
    if(_dataArray){
        return _dataArray.count;
    }
    
    return 0;
}

-(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    
    SectionModel *s = _dataArray[section];
    if(s.cells) {
        return s.cells.count;
    }
    return 0;
}

-(CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section {
    SectionModel *s = _dataArray[section];
    
    return s.headerhHeight;
}

-(CGFloat)tableView:(UITableView *)tableView heightForFooterInSection:(NSInteger)section {
    SectionModel *s = _dataArray[section];
    
    return s.footerHeight;
}

-(CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
    SectionModel *s = _dataArray[indexPath.section];
    CellModel *item = s.cells[indexPath.row];
    return item.height;
}

-(UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section {
    UITableViewHeaderFooterView *view = [tableView dequeueReusableHeaderFooterViewWithIdentifier:BKGDMainViewHeaderSectionViewIdentifier];
    view.contentView.backgroundColor = tableView.backgroundColor;
    return view;
}

-(UIView *)tableView:(UITableView *)tableView viewForFooterInSection:(NSInteger)section {
    UITableViewHeaderFooterView *view = [tableView dequeueReusableHeaderFooterViewWithIdentifier:BKGDMainViewFooterSectionViewIdentifier];
    view.contentView.backgroundColor = tableView.backgroundColor;
    return view;
}

-(UITableViewCell*)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    
    SectionModel *s = _dataArray[indexPath.section];
    CellModel *item = s.cells[indexPath.row];
    
    BKGDCell *cell = [tableView dequeueReusableCellWithIdentifier:item.reuseIdentifier];
    if(!cell) {
        cell = [[NSClassFromString(item.className) alloc] initWithStyle:item.style reuseIdentifier:item.reuseIdentifier];
    }
    
    cell.selectionStyle = item.selectionStyle;
    cell.accessoryType = item.accessoryType;
    cell.delegate = item.delegate;
    
    return cell;
}

-(void)tableView:(UITableView *)tableView willDisplayCell:(UITableViewCell *)cell forRowAtIndexPath:(NSIndexPath *)indexPath {
    
    SectionModel *s = _dataArray[indexPath.section];
    CellModel *item = s.cells[indexPath.row];
    
    if(item.title) {
        cell.textLabel.text = item.title;
        cell.textLabel.font = UIFontNormal;
        cell.textLabel.textColor = [UIColor colorWithRed:0.294 green:0.298 blue:0.302 alpha:1.00];
    }
    if(item.subTitle) {
        cell.detailTextLabel.text = item.subTitle;
        cell.detailTextLabel.font = UIFontNormal;
        cell.detailTextLabel.textColor = [UIColor colorWithRed:0.294 green:0.298 blue:0.302 alpha:1.00];
    }
    
    SEL selector = @selector(fillData:);
    if([cell respondsToSelector:selector]) {
#pragma clang diagnostic push
#pragma clang diagnostic ignored"-Warc-performSelector-leaks"
        [cell performSelector:selector withObject:item.userInfo];
#pragma clang diagnostic pop
    }
}

-(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
    [tableView deselectRowAtIndexPath:indexPath animated:YES];
    
    SectionModel *s = _dataArray[indexPath.section];
    CellModel *item = s.cells[indexPath.row];
    NSString *selectorString = item.selectorString;
    if(selectorString) {
        SEL selector = NSSelectorFromString(selectorString);
        if([self respondsToSelector:selector]) {
            ((void (*)(void *, SEL, NSIndexPath*))objc_msgSend)((__bridge void *)(self), selector, indexPath);
            /*
             等价于：void (*action)(void *, SEL, NSIndexPath*) = (void (*)(void *, SEL, NSIndexPath*))objc_msgSend;
                 action((__bridge void *)(self), selector, indexPath);
             即：[self 方法名:indexPath];
             */
        }
    }
}

#pragma scrollView delegate

-(void)scrollViewDidScroll:(UIScrollView *)scrollView {
    
    CGFloat offsetY = scrollView.contentOffset.y + 64;
    
    CGRect frame = _imageBrowserView.frame;
    
    if(offsetY <= 0 && offsetY >= -CGRectGetHeight(_imageBrowserView.frame)) {
        frame.origin.y = offsetY - (CGRectGetHeight(frame) + offsetY) / 2;
        _imageBrowserView.frame = frame;
    }
    
}

-(void)scrollViewDidEndDragging:(UIScrollView *)scrollView willDecelerate:(BOOL)decelerate {
    CGFloat offsetY = scrollView.contentOffset.y;
    CGFloat allowNextPageY = offsetY + scrollView.frame.size.height;
    
    if(allowNextPageY > scrollView.contentSize.height) {
        [self footerRefresh];
    }
}

#pragma -mark footer refresh

-(void)footerRefresh {
    
    //[_tableView.mj_footer endRefreshing];
    if(_delegate && [_delegate respondsToSelector:@selector(BKGDFooterRefreshing)]) {
        [_delegate BKGDFooterRefreshing];
    }
    
}

#pragma -mark CellDidSelect

/**
 sku选择
 */
-(void)skuCellDidSelectAtIndexPath:(NSIndexPath*)indexPath {
    CGRect screenRect = [[UIScreen mainScreen] bounds];
    CGFloat height = CGRectGetHeight(screenRect) * 0.7;
    CGRect startFrame = CGRectMake(0, CGRectGetHeight(screenRect), CGRectGetWidth(screenRect), height);
    CGRect endFrame = CGRectMake(0, CGRectGetHeight(screenRect) - height, CGRectGetWidth(screenRect), height);
    
    WUMenuView *menuView = [[WUMenuView alloc] initWithStartFrame:startFrame endFrame:endFrame];
    
    if(!_specificationController) {
        _specificationController = [[BKGDSpecificationController alloc] init];
        _specificationController.delegate = self;
        _specificationController.view.frame = CGRectMake(0, 0, CGRectGetWidth(menuView.endFrame), CGRectGetHeight(menuView.endFrame));
    }
    
    [menuView.contentView addSubview:_specificationController.view];
    _specificationController.goodsDetail = _goodsDetail;
    _specificationController.userInfo = @(-1);
    
    [menuView show];
}

-(void)showTipMenuView:(NSString*)title data:(NSArray<BKGDPopupItemModel*>*)data {
    CGRect screenRect = [[UIScreen mainScreen] bounds];
    CGFloat height = CGRectGetHeight(screenRect) / 2;
    CGRect startFrame = CGRectMake(0, CGRectGetHeight(screenRect), CGRectGetWidth(screenRect), height);
    CGRect endFrame = CGRectMake(0, CGRectGetHeight(screenRect) - height, CGRectGetWidth(screenRect), height);
    
    WUMenuView *menuView = [[WUMenuView alloc] initWithStartFrame:startFrame endFrame:endFrame];
    
    BKGDPopupViewController *popupController = [[BKGDPopupViewController alloc] init];
    popupController.view.frame = CGRectMake(0, 0, CGRectGetWidth(menuView.endFrame), CGRectGetHeight(menuView.endFrame));
    
    if(!_popupNavigationController) {
        _popupNavigationController = [[UINavigationController alloc] init];
        [_popupNavigationController.navigationBar setTitleTextAttributes:@{NSFontAttributeName: [UIFont systemFontOfSize:16]}];
        [_popupNavigationController.navigationBar setBarTintColor:[UIColor whiteColor]];
        [_popupNavigationController.navigationBar setClipsToBounds:YES];
        _popupNavigationController.view.frame = popupController.view.frame;
    }
    
    [_popupNavigationController setViewControllers:@[popupController]];
    
    BKGDPopupViewController *popupVC = _popupNavigationController.viewControllers[0];
    popupVC.title = title;
    popupVC.items = data;
    
    __weak typeof(menuView) weakMenuView = menuView;
    popupVC.closeBlock = ^ {
//        __strong typeof(weakMenuView) strongMenuView = weakMenuView;
//        [strongMenuView dismiss];
        [weakMenuView dismiss];
    };
    
    [menuView.contentView addSubview:_popupNavigationController.view];
    [menuView show];
}

-(NSArray<BKGDPopupItemModel*>*)popupQuotaData:(NSArray<BKGDMembershipPurchaseistObject*>*)data {
    if(!data || data.count == 0) {
        return nil;
    }
    
    NSMutableArray<BKGDPopupItemModel*> *array = [NSMutableArray array];
    UIColor *color = [UIColor colorWithRed:0.376 green:0.871 blue:0.608 alpha:1.00];
    for (BKGDMembershipPurchaseistObject *model in data) {
        BKGDPopupItemModel *item1 = [self createDefaultPopupItem];
        item1.content = model.level;
        [array addObject:item1];
        
        BKGDPopupItemModel *item2 = [self createDefaultPopupItem];
        item2.content = model.quotaMessage;
        [array addObject:item2];
        
        if(model.currentLevelFlag) {
            item1.textColor = color;
            item2.textColor = color;
        }
    }
    
    return array;
}

-(BKGDPopupItemModel*)createDefaultPopupItem {
    BKGDPopupItemModel *item = [[BKGDPopupItemModel alloc] init];
    item.font = [UIFont systemFontOfSize:12];
    item.textColor = [UIColor grayColor];
    item.size = CGSizeMake(CGRectGetWidth(self.view.frame) / 2, 40);
    item.textAlignment = NSTextAlignmentCenter;
    return item;
}

#pragma -mark SpecificationViewControllerDelegate

-(void)specification:(BKGDSpecificationController *)controller DidSelectedSKUObject:(BKGDSKUObject *)skuObject selectMessage:(NSString *)message {
    
    _goodsDetail.currentSelectSKUObject = skuObject;
    
    [self settingBottomViewItems];
    
    SectionModel *s = _dataArray[_skuCellIndexPath.section];
    CellModel *row = s.cells[_skuCellIndexPath.row];
    
    row.userInfo = [NSString stringWithFormat:@"%@ ×%ld", message, (long)controller.selectedCount];
    
    NSArray<NSIndexPath*> *needRefreshIndexPaths = @[_priceCellIndexPath, _subPriceCellIndexPath, _skuCellIndexPath];
    [_tableView reloadRowsAtIndexPaths:needRefreshIndexPaths withRowAnimation:UITableViewRowAnimationNone];
}

-(void)specification:(BKGDSpecificationController *)controller selectedCountChanged:(NSInteger)selectedCount {
    if(!_skuCellIndexPath) {
        return;
    }
    
    SectionModel *s = _dataArray[_skuCellIndexPath.section];
    CellModel *row = s.cells[_skuCellIndexPath.row];
    
    if(controller.selectedObject) {
        row.userInfo = [NSString stringWithFormat:@"%@ ×%ld", controller.selectedMessage, (long)controller.selectedCount];
    } else {
        row.userInfo = nil;
    }
    [_tableView reloadRowsAtIndexPaths:@[_skuCellIndexPath] withRowAnimation:UITableViewRowAnimationAutomatic];
}

-(void)specification:(BKGDSpecificationController *)controller bottomButtonTouchUpInside:(UIButton *)button {
    
    BKGDSKUObject *skuObject = controller.selectedObject;
    if(skuObject) {
        UIView *view = controller.view.superview;
        if(view && view.superview && [view.superview isKindOfClass:[WUMenuView class]]) {
            [((WUMenuView*)view.superview) dismiss];
            
            dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(300 * NSEC_PER_MSEC)), dispatch_get_main_queue(), ^{

                BKGDSKUObject *selectedObj = self.specificationController.selectedObject;
                NSInteger type = [_specificationController.userInfo integerValue];
                if(selectedObj.isBuy == 1 && type != -1) {
                    
                    if(selectedObj.saleType == 0 || selectedObj.saleType == 3) {//囤货
                        [self bid];
                    } else {//普通预购 或 固定出价
                        if(type == BKGDMainBottomViewItemTypeBuy) {//userInfo为自定义，表示 BKGDMainBottomViewItemType 默认-1
                            [self buy];
                        } else if(type == BKGDMainBottomViewItemTypeAddShoppingCar){
                            [self addShoppingCar];
                        }
                    }
                } else if(selectedObj.isBuy == 2) {//到货通知
                    if(!_goodsDetail.userLevel.loginFlag) {
                        [self goToLogin];
                        return;
                    }
                    [self arrivalNotice];
                }
                
            });
        }
    }
}

-(void)specificationDidTouchClose:(BKGDSpecificationController *)controller {
    UIView *view = controller.view.superview;
    if(view && view.superview && [view.superview isKindOfClass:[WUMenuView class]]) {
        [((WUMenuView*)view.superview) dismiss];
    }
}

#pragma -mark notice

-(void)taxCellHelpNotification:(NSNotification*)notification {
    [self showTipMenuView:BKGDLocalizedString(@"BKGDMainTaxMessage") data:[self popupTaxData:_goodsDetail.goodsTaxText]];
}

-(NSArray<BKGDPopupItemModel*>*)popupTaxData:(NSString*)text {
    if(!text) {
        return nil;
    }
    
    UIFont *font = [UIFont systemFontOfSize:12];
    CGSize size = [text boundingRectWithSize:CGSizeMake(CGRectGetWidth(self.view.frame) - 20, CGFLOAT_MAX) options:NSStringDrawingUsesLineFragmentOrigin attributes:@{NSFontAttributeName: font} context:nil].size;
    
    BKGDPopupItemModel *item = [[BKGDPopupItemModel alloc] init];
    item.content = text;
    item.font = font;
    item.textColor = [UIColor grayColor];
    item.numberOfLines = 0;
    item.size = CGSizeMake(size.width, size.height + 10);
    item.textAlignment = NSTextAlignmentLeft;
    
    return @[item];
}

#pragma -mark bottomView delegate

-(void)bottomView:(BKGDMainBottomView *)view didSelectAtType:(BKGDMainBottomViewItemType)type {

    if (type == BKGDMainBottomViewItemTypeBuy || type == BKGDMainBottomViewItemTypeBid) {
        if (_goodsDetail.goodscollect.canBuyAmount > 0) {
            [self handlerWithType:type];
        }else{
            [HUD showMessage:self.goodsDetail.goodscollect.quotaMessage];
        }
    }else{
        [self handlerWithType:type];
    }
}

-(void)handlerWithType:(BKGDMainBottomViewItemType)type {
    
    if(!_goodsDetail) {
        return;
    }
    
    if(!_goodsDetail.userLevel.loginFlag) {
        [self goToLogin];
        return;
    }
    
    switch (type) {
        case BKGDMainBottomViewItemTypeShoppingCar: {
            UIViewController *controller = [[Mediator sharedInstance] BKSC_shoppingCarViewController];
            controller.hidesBottomBarWhenPushed = YES;
            [self.navigationController pushViewController:controller animated:YES];
        }
            break;
        case BKGDMainBottomViewItemTypeFavorite:
        case BKGDMainBottomViewItemTypeFavoriteAlready: {
            [self favorite];
        }
            break;
        case BKGDMainBottomViewItemStockUpPreOrder: {
            BKGDManagerViewController *managerController = [[BKGDManagerViewController alloc] init];
            managerController.goodsId = _goodsId;
            managerController.saleTypes = _saleTypes;
            managerController.thnormaltype = 1;
            managerController.storeId = _storeId;
            managerController.shopKeeper = _shopKeeper;
            
            [self.navigationController pushViewController:managerController animated:YES];
        }
            break;
            
        case BKGDMainBottomViewItemTypeDisabled: {
            [HUD showMessage:BKGDLocalizedString(@"BKGDMainBuyDisabled")];
        }
            break;
            
        default: {
            BOOL isSpecificationSelected1 = _goodsDetail.propNumber > 0 && _specificationController.selectedObject;
            BOOL isSpecificationSelected2 = _goodsDetail.propNumber == 0 && (_goodsDetail.saleType == 0 || _goodsDetail.saleType == 3 || type == BKGDMainBottomViewItemTypeArrivalNotice);
            //是否已经规格选择，当sku可选 并且已经选择到    或者    sku不可选囤货
//            BOOL isSpecificationSelected = (_goodsDetail.propNumber > 0 && _specificationController.selectedObject) || (_goodsDetail.propNumber == 0 && _goodsDetail.saleType == 0);
            BOOL isSpecificationSelected = isSpecificationSelected1 || isSpecificationSelected2;
            if(isSpecificationSelected) {
                switch (type) {
                    case BKGDMainBottomViewItemTypeBid: {
                        [self bid];
                    }
                        break;
                    case BKGDMainBottomViewItemTypeBuy: {
                        [self buy];
                    }
                        break;
                    case BKGDMainBottomViewItemTypeAddShoppingCar: {
                        [self addShoppingCar];
                    }
                        break;
                    case BKGDMainBottomViewItemTypeArrivalNotice: {
                        [self arrivalNotice];
                    }
                        break;
                    default:
                        break;
                }
            } else {
                [self skuCellDidSelectAtIndexPath:_skuCellIndexPath];
                _specificationController.userInfo = @(type);
            }
        }
            break;
    }
}

/**
 配置底部菜单按钮项
 */
-(void)settingBottomViewItems {
    if(!_goodsDetail) {
        return;
    }
    
    if(self.parentViewController) {
        [self.parentViewController.view addSubview:_bottomView];
        [self.bottomView mas_makeConstraints:^(MASConstraintMaker *make) {
            make.left.mas_equalTo(0);
            make.bottom.mas_equalTo(0);
            make.width.mas_equalTo(CGRectGetWidth(self.view.frame));
            make.height.mas_equalTo(50);
        }];
    }
    
    self.bottomView.items = [self bottomItems];
}

-(NSArray<BKGDMainBottomViewItem*>*)bottomItems {
    CGFloat screenWidth = [[UIScreen mainScreen] bounds].size.width;
    CGFloat width = 64;
    
    NSMutableArray<BKGDMainBottomViewItem*> *items = [NSMutableArray array];
    BKGDMainBottomViewItem *shoppingCarItem = [[BKGDMainBottomViewItem alloc] initWithTitle:nil width:width type:BKGDMainBottomViewItemTypeShoppingCar];
    if(self.bottomView.items && self.bottomView.items.count > 0) {
        shoppingCarItem.badgeValue = self.bottomView.items[0].badgeValue;
    }
    [items addObject:shoppingCarItem];
    
    BKGDMainBottomViewItemType favoriteType = _goodsDetail.goodscollect.flag ? BKGDMainBottomViewItemTypeFavoriteAlready : BKGDMainBottomViewItemTypeFavorite;
    BKGDMainBottomViewItem *favoriteItem = [[BKGDMainBottomViewItem alloc] initWithTitle:nil width:width type:favoriteType];
    [items addObject:favoriteItem];
    
    CGFloat surplusWidth = screenWidth - 64 * 2;
    
    BKGDSKUObject *skuObject = _specificationController.selectedObject;
    NSString *text = skuObject ? skuObject.btnText :  _goodsDetail.btnText;
    NSInteger isBuy;
    NSInteger saleType;
    if(skuObject) {
        text = skuObject.btnText;
        isBuy = skuObject.isBuy;
        saleType = skuObject.saleType;
    } else {
        text = _goodsDetail.btnText;
        isBuy = _goodsDetail.isBuy;
        saleType = _goodsDetail.saleType;
    }
    
    if(isBuy == 0 && saleType != 3) {//不能购买
        BKGDMainBottomViewItem *disabledItem = [[BKGDMainBottomViewItem alloc] initWithTitle:text width:surplusWidth type:BKGDMainBottomViewItemTypeDisabled];
        [items addObject:disabledItem];
        
        return items;
    } else if(isBuy == 2) {//到货通知
        BKGDMainBottomViewItem *noticeItem = [[BKGDMainBottomViewItem alloc] initWithTitle:text width:surplusWidth type:BKGDMainBottomViewItemTypeArrivalNotice];
        [items addObject:noticeItem];
        
        return items;
    }
    //isBuy == 1 可以购买 或者 （saleType == 3 isBuy == 0）
    
    BOOL isCanBuy = _goodsDetail.goodscollect.canBuyAmount > 0; //限购量是否可买
    
    switch (saleType) { 
        case 0: {
            BKGDMainBottomViewItemType type = BKGDMainBottomViewItemTypeBid;
            BKGDMainBottomViewItem *bidItem = [[BKGDMainBottomViewItem alloc] initWithTitle:text width:surplusWidth type:type];
            [items addObject:bidItem];
        }
            break;
        case 1:
        case 2:
        case 4: {
            BKGDMainBottomViewItemType type = BKGDMainBottomViewItemTypeBuy;
            CGFloat width = surplusWidth / 2;
            if(isCanBuy) {
                BKGDMainBottomViewItem *shoppcarItem = [[BKGDMainBottomViewItem alloc] initWithTitle:nil width:width type:BKGDMainBottomViewItemTypeAddShoppingCar];
                type = BKGDMainBottomViewItemTypeBuy;
                [items addObject:shoppcarItem];
            } else {
                width = surplusWidth;
            }
            
            BKGDMainBottomViewItem *buyItem = [[BKGDMainBottomViewItem alloc] initWithTitle:text width:width type:type];
            [items addObject:buyItem];
        }
            break;
        case 3: {
            
            NSString *price1;
            NSString *price2;
            if(_goodsDetail.currentSelectSKUObject) {
                price1 = _goodsDetail.currentSelectSKUObject.price1;
                price2 = _goodsDetail.currentSelectSKUObject.price2;
            } else {
                price1 = _goodsDetail.price1;
                price2 = _goodsDetail.price2;
            }
            
            NSString *price = _goodsDetail.userLevel.vipFlag ? price1 : price2;
            NSString *supItemTitle = [NSString stringWithFormat:@"%@%@", price, BKGDLocalizedString(@"BKGDMainBottomStockUpPreOrder")];
            BKGDMainBottomViewItem *supItem = [[BKGDMainBottomViewItem alloc] initWithTitle:supItemTitle width:surplusWidth / 2 type:BKGDMainBottomViewItemStockUpPreOrder];
            [items addObject:supItem];
            
//            if(isBuy == 0 || !isCanBuy) {
//                BKGDMainBottomViewItem *disabledItem = [[BKGDMainBottomViewItem alloc] initWithTitle:text width:surplusWidth / 2 type:BKGDMainBottomViewItemTypeDisabled];
//                [items addObject:disabledItem];
//            } else {
                BKGDMainBottomViewItem *bidItem = [[BKGDMainBottomViewItem alloc] initWithTitle:text width:surplusWidth / 2 type:BKGDMainBottomViewItemTypeBid];
                [items addObject:bidItem];
//            }
        }
            break;
    }
    
    return items;
}

#pragma -mark 刷新购物车数量
-(void)refreshShoppingCarAmount {
    
    if(!self.bottomView.items || self.bottomView.items.count == 0) {
        return;
    }
    
    __weak typeof(self) weakSelf = self;
    
    [[Mediator sharedInstance] BKSC_getScAmount:^(NSString *amount) {
        NSLog(@"更新购物车数量：%@", amount);
        NSInteger value = [amount integerValue];
        NSString *badgeValue;
        if(value > 0) {
            badgeValue = [NSString stringWithFormat:@"%@", amount];
        }
        
        BKGDMainBottomViewItem *item = weakSelf.bottomView.items[0];
        item.badgeValue = badgeValue;
        UIViewController *rootViewController = [[[UIApplication sharedApplication] keyWindow] rootViewController];
        if([rootViewController isKindOfClass:[UITabBarController class]]) {
            ((UITabBarController*)rootViewController).tabBar.items[2].badgeValue = badgeValue;
        }
        
        [weakSelf.bottomView reloadAtIndex:0];
    }];
}

#pragma -mark bottom function
/**
 分享
 */
-(void)share {
    
    if(!_goodsDetail) {
        return;
    }
    
    if(!_goodsDetail.userLevel.loginFlag) {
        [self goToLogin];
        return;
    }
    
    __weak typeof(self) weakSelf = self;
    
    [[ShareManager manager] showShareMenuInController:self sharePlatformSelectionBlock:^ShareObject *(SharePlatformType type) {
       
        ShareObject *obj = [[ShareObject alloc] init];
        obj.title = weakSelf.goodsDetail.goodsName;
        obj.descr = weakSelf.goodsDetail.shareRemark;
        obj.thumbImage = weakSelf.goodsDetail.goodsImages ? weakSelf.goodsDetail.goodsImages[0] : @"";
        
        NSDictionary *userInfo = [[Mediator sharedInstance] BKMyUserInfo];
        NSString *value = userInfo[@"BKMyUserInfoUserVistorIdKey"];
        value = value ? value : @"";
        
        NSString *shareurl = [NSString stringWithFormat:@"%@%@%@?%@%@",BKGDWebURL,@"invite/",value,@"goods_no=",weakSelf.goodsDetail.goodsId];
        
        obj.webpageUrl = shareurl;
        return obj;
        
    } callBack:nil];
}

/**
 收藏
 */
-(void)favorite {
    BOOL isSave = _goodsDetail.goodscollect.flag;
    
    __weak typeof(self) weakSelf = self;
    
    NSString *path = isSave ? @"/collect/delete" : @"/collect/add";
    NSString *urlString = [NSString stringWithFormat:@"%@%@", BKGDServicesURL, path];
    NSDictionary *parameters = @{@"data": _goodsId};
    
    [[RequestManager manager] bkDataRequest:RequestMethodPost URLString:urlString parameters:parameters success:^(id  _Nullable responseObject) {
        
        BOOL success = [responseObject[@"success"] boolValue];
        if(success) {
            NSString *msg = responseObject[@"msg"];
            [HUD showSuccessMessage:msg];
            
            NSDictionary *data = responseObject[@"data"];
            if(data && data.count > 0) {
                weakSelf.goodsDetail.goodscollect.flag = !weakSelf.goodsDetail.goodscollect.flag;
            }
            
            BKGDMainBottomViewItem *item = weakSelf.bottomView.items[1];
            item.type = weakSelf.goodsDetail.goodscollect.flag ? BKGDMainBottomViewItemTypeFavoriteAlready : BKGDMainBottomViewItemTypeFavorite;
            
            [weakSelf.bottomView reloadAtIndex:1];
        }
        
        NSLog(@"收藏：%@", responseObject);
        
    } failure:^(id  _Nullable responseObject, NSError * _Nullable error) {
        NSLog(@"收藏错误：%@",error);
    }];
}

/**
 到货提醒
 */
-(void)arrivalNotice {
    BOOL iOS8AndLater = [[[UIDevice currentDevice] systemVersion] floatValue] >= 8.0;
    BOOL pushFlag = iOS8AndLater ? [[UIApplication sharedApplication] currentUserNotificationSettings] != 0 : [[UIApplication sharedApplication] enabledRemoteNotificationTypes] != UIRemoteNotificationTypeNone;
    
    if(pushFlag) {
        
        NSString *urlString = [NSString stringWithFormat:@"%@/goods-arrival-notify/add", BKGDServicesURL];
        NSDictionary *dict = [self generateParametersCurrent];
        
        NSDictionary *parameters = @{@"data": [dict mj_JSONString]};
        
        [[RequestManager manager] bkDataRequest:RequestMethodPost URLString:urlString parameters:parameters success:^(id  _Nullable responseObject) {
            NSString *msg = responseObject[@"msg"];
            [HUD showSuccessMessage:msg];
            
        } failure:^(id  _Nullable responseObject, NSError * _Nullable error) {
            NSLog(@"%@",error);
        }];
        
        
    } else {
        NSString *message = BKGDLocalizedString(@"BKGDMainAOGMessage");
        NSString *title = BKGDLocalizedString(@"BKGDMainAOGTitle");
        NSString *setting = BKGDLocalizedString(@"BKGDMainAOGOKActionTitle");
        NSString *cancel = BKGDLocalizedString(@"BKGDMainAOGCancelActionTitle");
        
        if (iOS8AndLater) {
            
            UIAlertController * alertContr = [UIAlertController alertControllerWithTitle:title message:message preferredStyle:UIAlertControllerStyleAlert];
            UIAlertAction * action = [UIAlertAction actionWithTitle:setting style:UIAlertActionStyleDestructive handler:^(UIAlertAction * _Nonnull action) {
                NSURL *url = [NSURL URLWithString:UIApplicationOpenSettingsURLString];
                [[UIApplication sharedApplication] openURL:url];
            }];
            
            UIAlertAction * action2 = [UIAlertAction actionWithTitle:cancel style:UIAlertActionStyleCancel handler:nil];
            
            [alertContr addAction:action];
            [alertContr addAction:action2];
            [self presentViewController:alertContr animated:YES completion:nil];
        } else {
            
            UIAlertView * alert = [[UIAlertView alloc]initWithTitle:title message:message delegate:self cancelButtonTitle:cancel otherButtonTitles: setting,nil];
            [alert show];
        }
    }
}

-(void)alertView:(UIAlertView *)alertView clickedButtonAtIndex:(NSInteger)buttonIndex
{
    if (buttonIndex == 1) {
        NSURL * url = [NSURL URLWithString:@"prefs:root=NOTIFICATIONS_ID"];
        [[UIApplication sharedApplication] openURL:url];
    }
}

/**
 立即出价
 */
-(void)bid {
    
    NSString *reserveId = _goodsDetail.propNumber == 0 ? _goodsDetail.skuList[0].skuId : _specificationController.selectedObject.skuId;
    NSDictionary *levelLimit = [NSDictionary dictionary];
    if(_goodsDetail.goodscollect) {
        levelLimit = [_goodsDetail.goodscollect mj_JSONObject];
    }
    NSMutableDictionary *orderInfo = [NSMutableDictionary dictionaryWithDictionary:[self generateParametersCurrent]];
    if(_goodsDetail.thnormalFlag) {
        [orderInfo setObject:@"1" forKey:@"thnormaltype"];
    }
    
    if (_storeId) {
        [orderInfo setObject:_storeId forKey:@"storeId"];
    }
    
    if (_shopKeeper) {
        [orderInfo setObject:_shopKeeper forKey:@"shopKeeper"];
    }
    
    NSDictionary *parameters = @{@"reserveId": reserveId, @"levelLimit": levelLimit, @"orderInfo": orderInfo};
    
    UIViewController *controller = [[Mediator sharedInstance] BKOrder_deliveryDateViewControllerWithParameter:parameters];
    if(controller) {
        controller.hidesBottomBarWhenPushed = YES;
        [self.navigationController pushViewController:controller animated:YES];
    }
}

/**
 立即购买
 */
-(void)buy {
    
    BKGDSKUObject *skuObj = _goodsDetail.propNumber == 0 ? _goodsDetail.skuList[0] : _specificationController.selectedObject;
    
    NSMutableDictionary *orderInfo = [NSMutableDictionary dictionaryWithDictionary:[self generateParametersCurrent]];
    [orderInfo setValue:@(_specificationController.selectedCount) forKey:@"amount"];
    [orderInfo setValue:skuObj.skuId forKey:@"goods_reserve_id"];
    
    
    NSString *sendDate = @"";
    NSString *userPrice = @"";
    if(skuObj.saleType == 2) {//固定出价
        sendDate = skuObj.fixednewlyday;
        userPrice = skuObj.fixedbidprice;
    }
    [orderInfo setValue:sendDate forKey:@"sendDate"];
    [orderInfo setValue:userPrice forKey:@"userPrice"];
    [orderInfo setValue:@"" forKey:@"integralGoodsId"];
    
    if(_goodsDetail.thnormalFlag) {
        [orderInfo setObject:@"1" forKey:@"thnormaltype"];
    }
    
    if (_storeId) {
        [orderInfo setObject:_storeId forKey:@"storeId"];
    }
    
    if (_shopKeeper) {
        [orderInfo setObject:_shopKeeper forKey:@"shopKeeper"];
    }
    
    NSDictionary *parameters = @{@"orderInfo": @[orderInfo]};
    
    UIViewController *controller = [[Mediator sharedInstance] BKOrder_orderViewControllerWithParameter:parameters];
    if(controller) {
        controller.hidesBottomBarWhenPushed = YES;
        [self.navigationController pushViewController:controller animated:YES];
    }
}

/**
 加入购物车
 */
-(void)addShoppingCar {
    
    BKGDSKUObject *skuObj = _goodsDetail.propNumber == 0 ? _goodsDetail.skuList[0] : _specificationController.selectedObject;
    
    NSMutableDictionary *orderInfo = [NSMutableDictionary dictionaryWithDictionary:[self generateParametersCurrent]];
    [orderInfo setValue:@(_specificationController.selectedCount) forKey:@"goods_amount"];
    NSString *sendDate = @"";
    NSString *userPrice = @"";
    if(skuObj.saleType == 2) {//固定出价
        sendDate = skuObj.fixednewlyday;
        userPrice = skuObj.fixedbidprice;
    }
    [orderInfo setValue:sendDate forKey:@"sendDate"];
    [orderInfo setValue:userPrice forKey:@"userPrice"];
    
    //saleType 0为囤货 1为普通预购 2为固定出价
    NSString *thbuyflag = skuObj.saleType == 0 || skuObj.saleType == 3 ? @"1" : skuObj.saleType == 1 || skuObj.saleType == 4 ? @"0" : @"2";
    [orderInfo setValue:thbuyflag forKey:@"thbuyflag"];
    
    if(_goodsDetail.thnormalFlag) {
        [orderInfo setObject:@"1" forKey:@"thnormaltype"];
    }
    
    if (_storeId) {
        [orderInfo setObject:_storeId forKey:@"storeId"];
    }
    
    if (_shopKeeper) {
        [orderInfo setObject:_shopKeeper forKey:@"shopKeeper"];
    }
    
    NSString *urlString = [NSString stringWithFormat:@"%@/shopping-cart/add", BKGDServicesURL];
    
    NSDictionary *parameters = @{@"data": [orderInfo mj_JSONString]};
    
    __weak typeof(self) weakSelf = self;
    
    [[RequestManager manager] bkDataRequest:RequestMethodPost URLString:urlString parameters:parameters success:^(id  _Nullable responseObject) {
       
        BOOL success = [responseObject[@"success"] boolValue];
        if(!success) {
            return;
        }
        
        NSString *msg = responseObject[@"msg"];
        
        [HUD showSuccessMessage:msg];
        
        [weakSelf refreshShoppingCarAmount];
        
    } failure:^(id  _Nullable responseObject, NSError * _Nullable error) {
        
    }];
}

-(void)goToLogin
{
    [[Mediator sharedInstance] userGoToLoginFromOrignalController:self finishBlock:^{
        [self requestGoodsDetailData];
    }];
    
}

/**
 根据当前用户选择的商品生成参数
 */
-(NSDictionary*)generateParametersCurrent {
    NSString *pids;
    if(_goodsDetail.propNumber > 0) {
        pids = _specificationController.selectedObject.skuProIds;
    } else {
        pids = _goodsDetail.skuList[0].skuProIds;
    }
    
    NSArray<NSString*> *array = [pids componentsSeparatedByString:@","];
    NSMutableDictionary *dict = [NSMutableDictionary dictionary];
    [dict setValue:_goodsDetail.goodsId forKey:@"goods_id"];
    [dict setValue:_goodsDetail.goodsImages forKey:@"goods_images"];
    [dict setValue:_goodsDetail.shareRemark forKey:@"shareRemark"];
    [dict setValue:_goodsDetail.goodsName forKey:@"goods_name"];
    NSString *keyPre = @"goods_pro_rel";
    for (int i = 0; i < array.count; i++) {
        NSString *value = array[i] ? array[i] : @"";
        [dict setValue:value forKey:[NSString stringWithFormat:@"%@%d", keyPre, i + 1]];
    }
    
    return [NSDictionary dictionaryWithDictionary:dict];
}

#pragma -mark data

/**
 请求商品详情数据
 */
-(void)requestGoodsDetailData {
    if(!_goodsId) {
        if(_maskView){
            [_maskView removeFromSuperview];
        }
        return;
    }
    
    __weak typeof(self) weakSelf = self;
    
    NSDictionary *userInfo = [[Mediator sharedInstance] BKMyUserInfo];
    
    NSString *urlString = [NSString stringWithFormat:@"%@/goods_v2/detail/%@", BKGDServicesURL, _goodsId];
    NSString *saleTypesParameter = _saleTypes && ![_saleTypes isEqual:[NSNull null]] ? _saleTypes : @"";
    NSString *thnormaltype = [NSString stringWithFormat:@"%ld", (long)_thnormaltype];
    
    NSDictionary *parameters;
    if ([_storeId isEqualToString:@""] && [_shopKeeper isEqualToString:@""]) {
        parameters = @{@"st": userInfo[BKMyUserGetUTOUUPlatformSTkey], @"thnormaltype": thnormaltype, @"saleTypes": saleTypesParameter};
    }else{
        parameters = @{@"st": userInfo[BKMyUserGetUTOUUPlatformSTkey], @"thnormaltype": thnormaltype, @"saleTypes": saleTypesParameter, @"storeId": _storeId, @"shopKeeper": _shopKeeper};
    }
    
//    NSDictionary *parameters = @{@"st": userInfo[BKMyUserGetUTOUUPlatformSTkey], @"thnormaltype": thnormaltype, @"saleTypes": saleTypesParameter};

    
    [LoadingView loadingShoppingCartInView:self.view];
    [[RequestManager manager] bkDataRequest:RequestMethodPost URLString:urlString parameters:parameters success:^(id  _Nullable responseObject) {
        if(!weakSelf) {
            return;
        }
        
        [LoadingView dismiss];
        
        __strong typeof(weakSelf) strongSelf = weakSelf;
        
        if(strongSelf.exceptionView) {
            [strongSelf.exceptionView dismiss];
            strongSelf.exceptionView = nil;
        }
        
        BOOL success = [responseObject[@"success"] boolValue];
        if(!success) {
            if([responseObject[@"code"] isEqualToString:@"020"]) {
//                NSString *msg = responseObject[@"msg"];
                [HUD showMessage:@"没有找到此商品"];
                [strongSelf.parentViewController.navigationController popViewControllerAnimated:YES];
            }
            if(_maskView){
                [_maskView removeFromSuperview];
            }
            return;
        }
        
        NSDictionary *dict = responseObject[@"data"];
        BKGDObject *goodsDetail = [BKGDObject mj_objectWithKeyValues:dict];
        [strongSelf analysisGoodsDetailData:goodsDetail];
        [strongSelf setGoodsDetailPrivate:goodsDetail];
        
        strongSelf.tableView.tableFooterView.hidden = NO;
        
        strongSelf.imageBrowserView.images = goodsDetail.goodsImages;
        [strongSelf.imageBrowserView refresh];
        [strongSelf bindGoodsDetailData:goodsDetail];
        
        [strongSelf settingBottomViewItems];
        [strongSelf refreshShoppingCarAmount];
        
        if(strongSelf.delegate && [strongSelf.delegate respondsToSelector:@selector(BKGDRequestCompleted)]) {
            [strongSelf.delegate BKGDRequestCompleted];
        }
        
        [strongSelf requestEvaluteInfo];

        
    } failure:^(id  _Nullable responseObject, NSError * _Nullable error) {
        NSLog(@"%@",error);
        if(!weakSelf) {
            return;
        }
        if(_maskView){
            [_maskView removeFromSuperview];
        }
        [LoadingView dismiss];
        
        __strong typeof(weakSelf) strongSelf = weakSelf;
        if(!strongSelf.exceptionView && error) {
            
            ExceptionCodeType errorViewType;
            if (error.code == -1009) {
                errorViewType = ExceptionCodeTypeNoNetwork;
            }else if (error.code == -1001){
                errorViewType = ExceptionCodeTypeRequestFailed;
            }else if (error.code == 502 || error.code == 404){
                errorViewType = ExceptionCodeTypeServerError;
            }else{
                errorViewType = ExceptionCodeTypeFailedToLoad;
            }
            
            strongSelf.exceptionView = [ExceptionView exceptionViewWithType:errorViewType];
            
            ExceptionViewAction *retryAction = [ExceptionViewAction actionWithType:errorViewType handler:^(ExceptionViewAction *action) {
                [strongSelf requestGoodsDetailData];
            }];
            [strongSelf.exceptionView addAction:retryAction];
            
            [strongSelf.exceptionView showInView:strongSelf.view];
            
        }
    }];
}

/**
 分析商品详情数据，并转化为客户端定义数据
 */
-(void)analysisGoodsDetailData:(BKGDObject*)goodsDetail {
    if(goodsDetail.thnormalFlag) {
        goodsDetail.saleType = 4;
    } else {
        if(goodsDetail.showThNormalbutton) {
            goodsDetail.saleType = 3;
        }
    }
    
    NSInteger saleType = goodsDetail.saleType;
    if(goodsDetail.skuList && goodsDetail.skuList.count > 0) {
        for (BKGDSKUObject *obj in goodsDetail.skuList) {
            //目前囤货预售没有针对SKU 只针对商品
            obj.saleType = saleType == 3 || saleType == 4 ? saleType : obj.saleType;
        }
    }
}

-(void)setGoodsDetailPrivate:(BKGDObject*)model {
    _goodsDetail = model;
    NSDictionary *userInfo = [[Mediator sharedInstance] BKMyUserInfo];
    _goodsDetail.userLevel.loginFlag = [userInfo[@"BKMyUserIsLoginKey"] boolValue];
}

/**
 请求商品详情评价概要
 */
-(void)requestEvaluteInfo {
    
    NSString *urlString = [NSString stringWithFormat:@"%@/goods-evaluation/evaluationInfo", BKGDServicesURL];
    NSDictionary *parameters = @{@"goodsId": _goodsId};
    
    __weak typeof(self) weakSelf = self;
    
    [[RequestManager manager] bkDataRequest:RequestMethodPost URLString:urlString parameters:parameters success:^(id  _Nullable responseObject) {
        
        if(!weakSelf) {
            return;
        }
        __strong typeof(weakSelf) strongSelf = weakSelf;
        
        BOOL success = [responseObject[@"success"] boolValue];
        if(!success) {
            [strongSelf bindEvaluteData:nil];
            return;
        }
        
        NSDictionary *dict = responseObject[@"data"];
        BKGDEvaluationGeneralObject *generalObj = [BKGDEvaluationGeneralObject mj_objectWithKeyValues:dict];
        [strongSelf bindEvaluteData:generalObj];
        
    } failure:^(id  _Nullable responseObject, NSError * _Nullable error) {
        NSLog(@"%@",error);
    }];
}

#pragma mark -- 绑定商品详情数据
-(void)bindGoodsDetailData:(BKGDObject*)data {
    
    if(!data) {
        return;
    }
    
    [_dataArray removeAllObjects];
    
    CellModel *nameModel = [self createCellModel:[BKGDTextCell class] userInfo:data height:[BKGDTextCell computeHeight:data]];
    CellModel *priceModel = [self createCellModel:[BKGDPriceCell class] userInfo:data height:[BKGDPriceCell computeHeight:data]];
    _priceCellIndexPath = [NSIndexPath indexPathForRow:1 inSection:0];
    CellModel *subPriceModel = [self createCellModel:[BKGDSubPriceCell class] userInfo:data height:[BKGDSubPriceCell computeHeight:data]];
    subPriceModel.delegate = self;
    _subPriceCellIndexPath = [NSIndexPath indexPathForRow:2 inSection:0];
    SectionModel *descSection = [self createSectionModel:@[nameModel, priceModel, subPriceModel] headerHeight:0.1 footerHeight:0.1];
    [_dataArray addObject:descSection];
    
    //跨境淘包含税费信息
    if([data.channelType isEqualToString:@"02"]) {
        CellModel *taxModel = [self createCellModel:[BKGDTaxCell class] userInfo:data height:[BKGDTaxCell computeHeight:data]];
        SectionModel *taxSection = [self createSectionModel:@[taxModel] headerHeight:1 footerHeight:0.1];
        [_dataArray addObject:taxSection];
    }
    
    //特色描述
    if(data.goodsFeatureDescribe && ![data.goodsFeatureDescribe isEqualToString:@""]) {
        CellModel *gfdModel = [self createCellModel:[BKGDFeatureDescribeCell class] userInfo:data.goodsFeatureDescribe height:[BKGDFeatureDescribeCell computeHeight:data.goodsFeatureDescribe]];
        SectionModel *gfdSection = [self createSectionModel:@[gfdModel] headerHeight:1 footerHeight:0.1];
        [_dataArray addObject:gfdSection];
    }
    
    //活动 促销
    if((data.activities && data.activities.count > 0) || (data.promotions && data.promotions.count > 0)) {
        CellModel *actPromModel = [self createCellModel:[BKGDPromotionCell class] userInfo:data height:[BKGDPromotionCell computeHeight:data]];
        
        BOOL isShowAccessoryPromotions = NO;
        if(data.activities.count > 0) {
            if(data.promotions.count > 1) {
                isShowAccessoryPromotions = YES;
            }
        } else {
            if(data.promotions.count > 2) {
                isShowAccessoryPromotions = YES;
            }
        }
        
        if(isShowAccessoryPromotions) {
            actPromModel.accessoryType = UITableViewCellAccessoryDisclosureIndicator;
        } else {
            actPromModel.accessoryType = UITableViewCellAccessoryNone;
        }
        
//        actPromModel.accessoryType = UITableViewCellAccessoryDisclosureIndicator;
        
        actPromModel.selectorString = @"promotionsDidSelected";
        
        SectionModel *apSection = [self createSectionModel:@[actPromModel] headerHeight:1 footerHeight:0.1];
        [_dataArray addObject:apSection];
    }
    
    //SKU
    if(data.propNumber > 0) {
        CellModel *skuModel = [self createCellModel:[BKGDSKUCell class] userInfo:nil height:[BKGDSKUCell computeHeight:@""]];
        if(_goodsDetail.isBuy == 0) {
            skuModel.accessoryType = UITableViewCellAccessoryNone;
            skuModel.userInfo = BKGDLocalizedString(@"BKGDMainBuyDisabled");
        } else {
            skuModel.accessoryType = UITableViewCellAccessoryDisclosureIndicator;
            skuModel.selectorString = NSStringFromSelector(@selector(skuCellDidSelectAtIndexPath:));
        }
        
        SectionModel *skuSection = [self createSectionModel:@[skuModel] headerHeight:10 footerHeight:0.1];
        [_dataArray addObject:skuSection];
        
        _skuCellIndexPath = [NSIndexPath indexPathForRow:0 inSection:_dataArray.count - 1];
    }
    
    //发货地
    if(data.sendAddress) {
        CellModel *sendAddressModel = [self createCellModel:[BKGDSendAddressCell class] userInfo:data height:[BKGDSendAddressCell computeHeight:data]];
        SectionModel *sendAddressSection = [self createSectionModel:@[sendAddressModel] headerHeight:10 footerHeight:0.1];
        [_dataArray addObject:sendAddressSection];
    }
    
    //7天退换货
    if (data.canReturnSaled) {
        CellModel *sevenDaysReturnModel = [self createCellModel:[BKGD7daysReturnCell class] userInfo:data height:[BKGD7daysReturnCell computeHeight:data]];
        SectionModel *sevenDaysSection = [self createSectionModel:@[sevenDaysReturnModel] headerHeight:0.5 footerHeight:0.1];
        [_dataArray addObject:sevenDaysSection];
    }
    
    //参数
    if(data.params && data.params.count) {
        
        NSString *propertyIdentifier = @"BKGDPropertyCellIdentifier";
        
        NSMutableArray<CellModel*> *properties = [NSMutableArray array];
        
        CellModel *propertyTextModel = [self createCellModel:[BKGDPTitleCell class] userInfo:BKGDLocalizedString(@"BKGDMainProperty") height:[BKGDPTitleCell computeHeight:@""]];
        [properties addObject:propertyTextModel];
        
        NSMutableArray *dataP = [NSMutableArray arrayWithArray:data.params];
        BKGDKeyValueObject *item = [[BKGDKeyValueObject alloc] init];
        item.key = @"";
        item.value = @"";
        [dataP addObject:item];
        
        for (BKGDKeyValueObject *item in dataP) {
            
            CellModel *propertyModel = [self createCellModel:[BKGDPropertyCell class] userInfo:item height:[BKGDPropertyCell computeHeight:item]];
            propertyModel.reuseIdentifier = propertyIdentifier;
            [properties addObject:propertyModel];
        }
        
      
        
        SectionModel *propertySection = [self createSectionModel:properties headerHeight:10 footerHeight:0.1];
        [_dataArray addObject:propertySection];
        
    }
    
    
    _dataArray.lastObject.footerHeight = 0.1;
    
    [_tableView reloadData];
    
    if(_maskView){
        [_maskView removeFromSuperview];
    }
}

-(CellModel*)createCellModel:(Class)cls userInfo:(id)userInfo height:(CGFloat)height {
    CellModel *model = [[CellModel alloc] init];
    model.selectionStyle = UITableViewCellSelectionStyleNone;
    model.userInfo = userInfo;
    model.height = height;
    model.className = NSStringFromClass(cls);
    return model;
}

-(SectionModel*)createSectionModel:(NSArray<CellModel*>*)items headerHeight:(CGFloat)headerHeight footerHeight:(CGFloat)footerHeight {
    SectionModel *model = [SectionModel sectionModelWithTitle:nil cells:items];
    model.headerhHeight = headerHeight;
    model.footerHeight = footerHeight;
    return model;
}

-(void)promotionsDidSelected {
    
    
    BKGDAddPriceBuyViewController *addBuy = [[BKGDAddPriceBuyViewController alloc] init];
    addBuy.goodsCoverImg = self.goodsCoverImg;
    [self.navigationController pushViewController:addBuy animated:YES];
    
//    BOOL isShow1 = _goodsDetail.activities.count > 0 && _goodsDetail.promotions.count > 1;
//    BOOL isShow2 = _goodsDetail.activities.count == 0 && _goodsDetail.promotions.count > 2;
//    
//    if(!isShow1 && !isShow2) {
//        return;
//    }
//    
//    CGRect screenRect = [[UIScreen mainScreen] bounds];
//    CGFloat height = CGRectGetHeight(screenRect) / 2;
//    CGRect startFrame = CGRectMake(0, CGRectGetHeight(screenRect), CGRectGetWidth(screenRect), height);
//    CGRect endFrame = CGRectMake(0, CGRectGetHeight(screenRect) - height, CGRectGetWidth(screenRect), height);
//    
//    WUMenuView *menuView = [[WUMenuView alloc] initWithStartFrame:startFrame endFrame:endFrame];
//    
//    BKGDPromotionsViewController *pvController = [[BKGDPromotionsViewController alloc] init];
//    pvController.view.frame = CGRectMake(0, 0, CGRectGetWidth(menuView.endFrame), CGRectGetHeight(menuView.endFrame));
//    
//    if(!_popupNavigationController) {
//        _popupNavigationController = [[UINavigationController alloc] init];
//        [_popupNavigationController.navigationBar setTitleTextAttributes:@{NSFontAttributeName: [UIFont systemFontOfSize:16]}];
//        [_popupNavigationController.navigationBar setBarTintColor:[UIColor whiteColor]];
//        [_popupNavigationController.navigationBar setClipsToBounds:YES];
//        _popupNavigationController.view.frame = pvController.view.frame;
//    }
//    
//    [_popupNavigationController setViewControllers:@[pvController]];
//    pvController.title = @"促销";
//    pvController.data = self.goodsDetail;
//    
//    __weak typeof(menuView) weakMenuView = menuView;
//    pvController.closeBlock = ^ {
//        __strong typeof(weakMenuView) strongMenuView = weakMenuView;
//        [strongMenuView dismiss];
//    };
//    
//    [menuView.contentView addSubview:_popupNavigationController.view];
//    [menuView show];
}

/**
 向tableView绑定商品评价概要数据
 */
-(void)bindEvaluteData:(BKGDEvaluationGeneralObject*)data {
    
    CellModel *evaluteModel;
    if(data) {
        evaluteModel = [self createCellModel:[BKGDEvaluationCell class] userInfo:data height:[BKGDEvaluationCell computeHeight:data]];
        evaluteModel.delegate = self;
    } else {
//        evaluteModel = [CellModel cellModelWithTitle:BKGDLocalizedString(@"BKGDMainEvaluation") subTitle:BKGDLocalizedString(@"BKGDMainEvaluationEmpty") image:nil sel:@"toEvaluationPage"];
//        evaluteModel.className = NSStringFromClass([BKGDCell class]);
//        evaluteModel.style = UITableViewCellStyleValue1;
//        evaluteModel.accessoryType = UITableViewCellAccessoryDisclosureIndicator;
//        evaluteModel.height = 45;
       evaluteModel = [self createCellModel:[BKGDEvaluatTitleCell class] userInfo:data height:[BKGDEvaluatTitleCell computeHeight:data]];
    }
    SectionModel *evaluteSection = [SectionModel sectionModelWithTitle:nil cells:@[evaluteModel]];
    evaluteSection.headerhHeight = 10;
    evaluteSection.footerHeight = 0.1;
    
    id lastItemData = _dataArray.lastObject.cells.lastObject.userInfo;
    
    //如果是参数cell 移动到最后显示
    if(lastItemData && [lastItemData isKindOfClass:[BKGDKeyValueObject class]]) {
        NSInteger index = _dataArray.count - 1;
        [_dataArray insertObject:evaluteSection atIndex:index];
        [_tableView insertSections:[NSIndexSet indexSetWithIndex:index] withRowAnimation:UITableViewRowAnimationNone];
    } else {
        [_dataArray addObject:evaluteSection];
        [_tableView insertSections:[NSIndexSet indexSetWithIndex:_dataArray.count - 1] withRowAnimation:UITableViewRowAnimationNone];
    }
}

#pragma -mark BKGDEvaluationCellDelegate
-(void)evaluationCell:(BKGDEvaluationCell *)cell bottomButtonTouched:(UIButton *)button {
    [self toEvaluationPage];
}

#pragma -mark BKGDSubPriceCellDelegate
-(void)subPriceCellBecomeVIPDidTouched:(BKGDSubPriceCell *)cell {
    if(_goodsDetail.userLevel.loginFlag) {
        BKGDBecomeVIPViewController *controller = [[BKGDBecomeVIPViewController alloc] init];
        [self.navigationController pushViewController:controller animated:YES];
    } else {
        [self goToLogin];
    }
}

/**
 转到评价页面
 */
-(void)toEvaluationPage {
    [[NSNotificationCenter defaultCenter] postNotificationName:BKGDManagerViewControllerMoveToPageNotificationKey object:@(2)];
}

#pragma -mark pop Notification 

-(void)popBKGDManagerHandler:(NSNotification*)notification {
    UIViewController *controller = self.navigationController.viewControllers.lastObject;
    if(!controller) {
        return;
    }
    
    NSString *controllerName = NSStringFromClass([controller class]);
    if(!controllerName) {
        return;
    }
    
    if([controllerName isEqualToString:NSStringFromClass([BKGDManagerViewController class])]) {
        [self refreshShoppingCarAmount];
    }
}

#pragma -mark dealloc
-(void)dealloc {
    [[NSNotificationCenter defaultCenter] removeObserver:self];
}

@end
